package org.jeecg.config.mybatis;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Component;

/**
 * @author Yann
 * @Date 2019/10/8
 * Mybatis plus 自动填充配置类
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    private static final String CREATE_TIME = "createTime";
    private static final String CREATE_BY = "createBy";
    private static final String UPDATE_TIME = "updateTime";
    private static final String UPDATE_BY = "updateBy";
    private static final String IS_DELETED = "isDeleted";
    private static final String VERSION = "version";
    private static final String SYS_ORG_CODE = "sysOrgCode";

    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser loginUser = getLoginUser();
        if (metaObject.hasGetter(CREATE_TIME)) {
            this.setFieldValByName(CREATE_TIME, DateUtil.date(), metaObject);
        }
        if (metaObject.hasGetter(IS_DELETED)) {
            this.setFieldValByName(IS_DELETED, Boolean.FALSE, metaObject);
        }
        if (metaObject.hasGetter(VERSION)) {
            this.setFieldValByName(VERSION, 0, metaObject);
        }
        if (metaObject.hasGetter(SYS_ORG_CODE)) {
            this.setFieldValByName(SYS_ORG_CODE, loginUser != null ? loginUser.getOrgCode() : null, metaObject);
        }
        if (metaObject.hasGetter(CREATE_BY)) {
            this.setFieldValByName(CREATE_BY, loginUser != null ? loginUser.getUsername() : "0", metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LoginUser loginUser = getLoginUser();

        if (metaObject.hasGetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, DateUtil.date(), metaObject);
        }

        if (metaObject.hasGetter(UPDATE_BY)) {
            this.setFieldValByName(UPDATE_BY, loginUser != null ? loginUser.getUsername() : "0", metaObject);
        }
    }

    private LoginUser getLoginUser() {
        LoginUser sysUser = null;
        try {
            sysUser = SecurityUtils.getSubject().getPrincipal() != null ?
                    (LoginUser) SecurityUtils.getSubject().getPrincipal() : null;
        } catch (Exception e) {
            sysUser = null;
        }
        return sysUser;
    }
}
